package com.lagou.filter;

import com.lagou.filter.component.ConsumerMetrics;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.support.RpcUtils;


@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

  @Override
  public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    URL url = invoker.getUrl();
    if (RpcUtils.isAsync(url, invocation)) {
      return invoker.invoke(invocation);
    }

    // 计算并保存调用时间
    long startTime = System.currentTimeMillis();
    Result result = invoker.invoke(invocation);
    long costTime = System.currentTimeMillis() - startTime;
    ConsumerMetrics.Metrics metrics = new ConsumerMetrics.Metrics(url, costTime, startTime);
    String fullMethodName = invocation.getServiceName() + "." + invocation.getMethodName();
    ConsumerMetrics.getInstance().putMetrics(fullMethodName, metrics);
    return result;
  }
}
